import random

import requests

from utils.myredis import r
from views.base import BaseHandler
import json
from db import db
from utils.myjwt import myjwt
import time
from utils.captcha.captcha import captcha
from utils.comm import send_message


# 图片验证码
class ImgCode(BaseHandler):
    def get(self):
        # 调用captcha生成图片验证码   text:信息   img:流
        name, text, img = captcha.generate_captcha()
        # 获取uuid
        uuid = self.get_query_argument("uuid")
        print("图片验证码>>", text)
        # 存入redis 字符串 key :uuid value:text
        r.str_setex(uuid, text, 300)
        # res = r.str_get(uuid)
        # print("缓存图片",res.decode())
        # 去头部配置Content-Type为：image/jpg
        self.set_header('Content-Type', "image/jpg")
        self.write(img)

    # 获取手机号按钮校验
    def post(self):
        data = json.loads(self.request.body)
        mobile = data["mobile"]
        imagecode = data["imagecode"]
        uuid = data["uuid"]
        if not all([mobile, imagecode]):
            return self.finish({"code": 400, "msg": "字段不能为空"})
        # 从redis中取出uuid
        res = r.str_get(uuid)
        # 判断是否存在
        if res:
            # 判断是否正确
            if res.decode().lower() != imagecode.lower():
                return self.finish({"code": 400, "msg": "图片验证码错误"})
            # 删除存在redis中的uuid
            r.del_key(uuid)
        else:
            return self.finish({"code": 400, "msg": "图片验证码已过期"})
        # 一分钟只能发送一次验证码，先判断队列里是否有
        s = r.str_get(mobile)
        if s:
            return self.finish({"code": 400, "msg": "一分钟内只能发送一次"})
        # 获取当前请求ip
        IP = self.request.remote_ip
        # 1.使用hash实现
        key = IP + 'iplist'
        # 获取存的数据
        ip = r.hash_getall(key)
        # 如果存在
        if ip:
            # 获取缓存中的时间
            t = r.hash_getone(key, 'time')
            #  查看是否过期
            # 当前时间 - 缓存中的时间 大于60
            if int(time.time()) - int(t.decode()) > 60:
                # 删除缓存
                r.del_key(key)
                return self.finish({"code": 400})
            else:
                # 获取缓存中的获取验证码的次数
                count = r.hash_getone(key, 'count')
                if int(count) >= 3:
                    return self.finish({"code": 400, "msg": "同一个IP，一分钟内不得连续三次获取验证码"})
                else:
                    # 对缓存中的次数加1
                    r.jiajian_hash(key, 'count', 1)
        else:
            r.hash_add(key, 'time', int(time.time()))
            r.hash_add(key, 'count', 1)

        # # 2.使用字符串实现
        # v = r.str_get(IP)
        # if v:
        #     strlist = v.decode().split(':')
        #     if int(strlist[0]) > 3:
        #         return self.finish({
        #             'code': 400,
        #             'msg': "同一个IP，一分钟内不得连续三次获取验证码"
        #         })
        #     sum = int(strlist[0]) + 1
        #     times = 60 - (int(time.time()) - int(strlist[1]))
        #     v = str(sum) + ':' + str(int(strlist[1]))
        #     r.str_setex(IP, v, times)
        # else:
        #     r.str_setex(IP, str(1) + ':' + str(int(time.time())), 60)
        #
        # # 如果没有，就将当前手机号加入redis
        r.list_push("smsmobile", mobile)
        self.write({"code": 200, "msg": "ok"})


# 获取短信验证码
class Send(BaseHandler):
    def get(self):
        while True:
            for i in range(2):
                # 查看队列长度
                len = r.list_len("smsmobile")
                if len > 0:
                    # 获取队列中的手机号
                    data = r.list_pop("smsmobile")
                    mobile = data.decode()
                    # 获取四位随机数
                    code = random.randint(1000, 9999)
                    # 获取验证码
                    res = send_message(mobile, code)
                    print("短信验证码>>>>>>>>>>>>>>>>>>>>>>>>>", code)
                    # 将手机号和验证码加入redis
                    r.str_setex(mobile, code, 60)
            time.sleep(1)
            # return "获取验证码成功"
            self.write("获取验证码成功")
            return


# 登录/注册
class Login(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        mobile = data["mobile"]
        smscode = data["smscode"]
        code = r.str_get(mobile)
        if code:
            if json.dumps(smscode) != json.dumps(code.decode()):
                return self.finish({"code": 400, "msg": "手机验证码错误"})
            r.del_key(mobile)
            sql = "select * from user where mobile = %d" % int(mobile)
            res = db.findone(sql)
            if res:
                data = {"data": {"userid": res["id"], "mobile": res["mobile"], "exptime": int(time.time())}}
                token = myjwt.jwt_encode(data)
                return self.finish(
                    {"code": 200, "msg": "登录成功", "token": token, "userid": res["id"], "mobile": res["mobile"]})
            sql1 = "insert into user(mobile) values (%d)" % int(mobile)
            db.add(sql1)
            db.commit()
            return self.finish({"code": 201, "msg": "注册成功"})
        else:
            return self.finish({"code": 400, "msg": "验证码已过期"})


# 三方登录
class Wburl(BaseHandler):
    def get(self):
        client_id = "3674019597"
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        # 微博平台地址
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
            client_id, redirect_uri)
        return self.finish({"code": 200, 'url': url})


# 回调
class WeiboCallback(BaseHandler):
    def get(self):
        # 获取code
        code = self.get_query_argument("code")
        print("code", code)
        # 向access_token接口发送post请求
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        # 获取https://api.weibo.com/oauth2/access_token信息  token   uid
        res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        # 根据返回结果操作
        # 先json转为字点获取token和uid
        message = json.loads(res.text)
        token = message['access_token']
        uid = message['uid']
        # 查询uid在数据库中是否存在，如果存在用用户信息生成jwt token返回
        sql = "select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'" % (
            str(uid))
        user = db.findone(sql)
        # 如果存在
        if user:
            # 生成jwt
            # 返回jwt token
            token = myjwt.jwt_encode(
                data={"data": {"uid": user['id'], "mobile": user['mobile'], 'exp': int(time.time())}})
            # 生成token，跳转到vue中转页，保存token到
            self.redirect("http://localhost:8080/updatetoken?token=" + token + "&userid=" + str(user['id']))

        else:
            # 不存在，就跳转到绑定手机号页面
            self.redirect("http://localhost:8080/wblogin?token=" + str(token) + "&uid=" + str(uid))


# 三方登录绑定手机号页面
class Setsf(BaseHandler):
    def post(self):
        # 接收参数
        data = json.loads(self.request.body)
        # 先判断手机号是否在用户表中存在
        sql = "select * from user where mobile='%s'" % (data["mobile"])
        res = db.findone(sql)
        if res:
            # 加入用户表
            sql2 = "insert into sf_login(userid,webfrom,uid,token) values(%d,'weibo','%s','%s')" % (
                int(res['id']), data['uid'], data['token'])
            db.add(sql2)
            db.commit()
            # 返回jwt token
            token = myjwt.jwt_encode(
                data={"data": {"uid": int(res['id']), "mobile": data['mobile'], 'exp': int(time.time())}})
            return self.finish({"code": 200, "token": token, "userid": int(res['id'])})
        else:
            # 加入用户表
            sql = "insert into user(mobile) values('%s')" % (data['mobile'])
            userid = db.add(sql)
            print("userid>>>>", userid)
            # 加入三方登录表
            sql2 = "insert into sf_login(userid,webfrom,uid,token) values(%d,'weibo','%s','%s')" % (
                userid, data['uid'], data['token'])
            db.add(sql2)
            db.commit()
            # 返回jwt token
            token = myjwt.jwt_encode(data={"data": {"uid": userid, "mobile": data['mobile'], 'exp': int(time.time())}})
            return self.finish({"code": 200, "token": token, "userid": userid})

# 七牛获取token
from qiniu import Auth
#需要填写你的 Access Key 和 Secret Key
class Qntoken(BaseHandler):
    def post(self):
        access_key = 'yQBox94ywYZZZfQ5LXKWk6KXc4MMQLcsQdIdBlll'
        secret_key = 'UWf2ZN9Jb21za02YBOXDL4V2hAavLdtBZHhh9U1Z'
        #构建鉴权对象
        q = Auth(access_key, secret_key)
        #要上传的空间
        bucket_name = 'p2pproject'
        #生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name)
        return self.finish({"code": 200, "msg":"获取成功","token":token})

from utils.bdapi import bd
class Bd(BaseHandler):
    def get(self):
        url = self.get_query_argument("url")
        res = bd.getmes(url)
        name = res[0]['words']
        ID_user = res[1]['words']
        return self.finish({"code": 200, "msg": "获取成功", "name": name,"ID_user":ID_user})

import uuid,os
class Locality(BaseHandler):
    def post(self):
        # 获取到前端传递过来的流（file）
        file = self.request.files.get("file",None)
        for i in file:
            # filename:流中的图片名
            filename = i["filename"]
            # filename:微信图片_20230213114351.png
            # 用点分割把png分隔下来
            # 对图片重命名
            arr = filename.split(".")
            #  .hex意在去除uuid中的横杠(-)
            name = uuid.uuid1().hex
            # 唯一值 + . + 后缀png
            newname = name + "." + arr[1]
            # 在urls里面配置的存储路径
            path = os.path.join(self.settings["MEDIA_ROOT"],newname)
            with open(path,'wb') as a:
                a.write(i["body"])
            # 加入队列解决qps限制
            r.list_rpush("baiduapi",path)
            print("path", path)
            return self.finish({"code": 200, "url":path})
            # content = bd.contentmes(path)
            # print("content>>>>>>",content)
            # aa=json.loads(content)
            # return self.finish({"code": 200, "msg": "获取成功", "name": aa["words_result"][0]['words'],"ID_user":aa["words_result"][1]['words'],"url":path})

# import time
# 定时任务解决qps限制
def getBaidu():
    while True:
        list = r.list_GetAll("baiduapi",0,1)
        if list:
            for i in list:
                content = bd.contentmes(i)
                r.set_str(i,json.dumps(content))
                r.list_lpop("baiduapi")
                print(">>>>执行中")
            time.sleep(1)
        return


# SetInterval: 定时任务
class SetInterval(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        path = data["url"]
        res = r.str_get(path)
        paths = res.decode()
        if paths:
            c = json.loads(paths)
            a = json.loads(c)
            # print(type(c))
            # print("c",c)
            # print("a",a)
            name = a['words_result'][0]['words']
            code = a['words_result'][1]['words']
            # print("name",name)
            self.finish({'code1': 200, 'msg': 'ok', 'name': name, 'code': code})
            r.del_key(path)





